import pymysql
from pymysql.cursors import DictCursor

from mysql_config import *

try:
    # 建立连接
    print('正在连接数据库...')
    connection = pymysql.connect(
        host=host,
        port=port,
        user=user,
        password=password,
        database=database,
        cursorclass=DictCursor  # 使用字典游标
    )
    print('成功连接数据库')

    with connection.cursor() as cursor:
        # 执行 SQL 查询
        sql = f"SELECT * FROM {table}"
        cursor.execute(sql)
        result = cursor.fetchall()
        print("Total number of rows in table: ", cursor.rowcount)

        print("\nPrinting each row")
        for row in result:
            print(row)

except pymysql.MySQLError as e:
    print(f"Error while connecting to MySQL: {e}")

finally:
    # 关闭连接
    if connection.open:
        connection.close()
        print("MySQL connection is closed")